package model

import (
	"errors"
	"github.com/jmoiron/sqlx"
	"time"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/pkg/e"
)

type UsdtLog struct {
	Id               int64   `db:"id" json:"id"`
	Uid              int64   `db:"uid" json:"uid"`
	Amount           float64 `db:"amount" json:"amount"`
	Balance          float64 `db:"balance" json:"balance"`
	UsdtLogId        int64   `db:"usdt_log_id" json:"usdt_log_id"`
	RechargeId       string  `db:"recharge_id" json:"recharge_id"`
	TokenOrderId     int64   `db:"token_order_id" json:"token_order_id"`
	From             string  `db:"from" json:"from"`
	To               string  `db:"to" json:"to"`
	Txhash           string  `db:"txhash" json:"txhash"`
	Source           int64   `db:"source" json:"source"`
	Status           int64   `db:"status" json:"status"`
	CreateTime       int64   `db:"create_time" json:"create_time"`
	UpdateTime       int64   `db:"update_time" json:"update_time"`
	Block            int64   `db:"block" json:"block"`
	BlockConfirmTime int64   `db:"block_confirm_time" json:"block_confirm_time"`
	SignString       string  `db:"sign_string" json:"sign_string"`
	SignVersion      string  `db:"sign_version" json:"sign_version"`
}

type UsdtBalance struct {
	Area    int     `json:"area"`
	Mobile  string  `json:"mobile"`
	Balance float64 `json:"balance"`
}

//插入Usdt_LOG记录
func InsertUsdtLog(db sqlx.Execer, data UsdtLogDB) error {
	_, err := db.Exec("INSERT INTO usdt_log (`uid`, `amount`, `balance`,`relate_id`, `relate_table`, `source`,`status`, `create_time`) "+
		" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
		data.Uid, data.Amount, data.Balance, data.RelateId, data.RelateTable, data.Source, data.Status, data.CreateTime)
	if err != nil {
		e.Log("err", err.Error())
		return errors.New("插入Usdt流水失败")
	}
	return nil
}

//修改USDT_AMOUNT 的可用余额
func UpdateUsdtAmountBlance(db sqlx.Execer, balance float64, uid int64) (err error) {
	res, err := db.Exec("UPDATE `usdt_amount` SET `balance` = ? WHERE `uid` = ?",
		balance, uid)
	if err != nil {
		e.Log("err", uid, balance, err.Error())
	} else if rows, _ := res.RowsAffected(); rows <= 0 {
		e.Log("err", "UpdateuUsdtAmountBlance", uid, balance, "无修改")
		err = errors.New("修改可用余额失败")
	}
	return
}

/*
 * @ Author: hupfei
 * @ Description: usdt_amount
 **/
func GetUsdtAmountByUid(uid int64) (user UsdtAmount, err error) {
	err = sqlx.Get(config.C.DB.DB, &user, "SELECT balance, create_time, update_time, sign_string, sign_version FROM usdt_amount WHERE uid = ?", uid)
	if err != nil {
		e.Log("err", "获取usdt_amount信息失败:", err.Error())
	}
	return user, err
}

/*
 * @ Author: hupfei
 * @ Description: 初始化usdt_amount
 **/
func InitUsdtAmount(uid int64, signString, signVersion string) (err error) {
	notTime := time.Now().Unix()
	_, err = config.C.DB.DB.Exec("INSERT INTO usdt_amount (uid,create_time,update_time,sign_string,sign_version) VALUES (?,?,?,?,?)", uid, notTime, notTime, signString, signVersion)
	if err != nil {
		e.Log("err", "初始化usdt_amount失败:", err.Error())
	}
	return
}
